package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: 李旭
 * @create: 2021-07-20 15:23
 **/
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {


    @Autowired
    private CartInfoService cartInfoService;
    //加入购物车
    @PostMapping("/addCart/{skuId}/{skuNum}")
    public void addCart(
            @PathVariable Long skuId,
            @PathVariable Integer skuNum, HttpServletRequest request
            ){
        //真实用户ID
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addCart(skuId,skuNum,userId);
    }

    //查询购物车
    @GetMapping("/getCartInfoBySkuId/{skuId}")
    public CartInfo getCartInfoBySkuId(@PathVariable Long skuId){
        return cartInfoService.getCartInfoBySkuId(skuId);
    }
    //去购物车结算
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
        return Result.ok(cartInfoList);
    }
    //选中
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked
    ,HttpServletRequest request){
        //真实用户ID
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(skuId,isChecked,userId);
        return Result.ok();
    }

    //商品清单
    @GetMapping("/getCartInfoCheckedList")
    public List<CartInfo> getCartInfoCheckedList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.getCartInfoCheckedList(userId);
    }
}
